<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm :fieldList="fieldList" :options="formOption" :formData="form"> </XForm>
      </template>
      <template #toolbar_btns>
        <div class="ml-auto"></div>
        <VButton type="" @click="importHandleClick">
          <div class="dk-iconfont icon-Upload"></div>
            导出
        </VButton>
        <el-button type="primary" @click="TableColumnConfigRef.open()">字段选择</el-button>
      </template>
      <template #HeaderContent="{ column }">
        <div>
          {{ column.title }}
        </div>
        <span v-if="column.title.includes('率')"> （%） </span>
        <span v-else-if="!'销售人员,订单量,订单量（目标）,日均订单量(目标),当期应完成订单量(目标),环比增长订单量'.includes(column.title)"> （{{ currency }}） </span>

        <el-tooltip class="box-item" effect="dark" :content="tips?.[column.field] || ''" placement="top" raw-content v-if="tips?.[column.field]">
          <div class="dk-iconfont icon-QuestionFilled"></div>
        </el-tooltip>
      </template>

      <template #footerRate="{ row, column }">
        {{ row[column.field] }}
        <el-tooltip class="box-item" effect="dark" :content="rateTip?.[column.field] || ''" placement="top" raw-content>
          <div class="dk-iconfont icon-QuestionFilled"></div>
        </el-tooltip>
      </template>

      <template #RateTem="{ row, column }"> {{ row[column.field] }}% </template>
    </VTable>
    <TableColumnConfig ref="TableColumnConfigRef" :api="displayField" scope="kpi" @initTable="initTableColumn" />
  </VPage>

  <!-- 导出中心 -->
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus"
import XForm from "@/components/XForm/index.vue"
import { kpiMember, displayField } from "./api"
import { reportAuthList } from "@/Auth/report.js"
import { ref, toRefs, reactive, onMounted } from "vue"


// 导出中心
import DerivedCenter from "@/components/DerivedCenter"
const DerivedCenterRef = ref()
const importHandleClick = async (e) => {
  let condition = tableRef.value.getQueryForm()
  condition.time_range = [`${condition.time_range}-01 00:00:00`, `${getLastDayOfMonth(condition.time_range)} 23:59:59`]

  DerivedCenterRef.value.open({
    tag_name: "sales_kpi",
    condition,
  })
}

const publicStyle = { style: { width: "220px" } }

import TableColumnConfig from "./tableColumnConfig"
const TableColumnConfigRef = ref()
const tableRef = ref()

const tips = {
  order_quantity_daily_target: "日均订单量(目标)= 日均订单量（目标）/ 本月总天数", // 日均订单量
  order_quantity_need_finish: "当期应完成订单量(目标)= 日均订单量 * 当月已过天数(包含今天)", // 当期应完成订单量
  order_quantity_achieving_rate: "订单量达成率（%）=订单量/订单量(目标)* 100%", // 订单量达成率
  order_quantity_need_finish_rate: "当期订单量达成率（%）= 订单量(实际)/当期应完成订单量(目标)* 100%", // 当期订单量达成率
  order_quantity_finish: "按付款时间查询，过滤新建订单原因为“做账”类型的手动新增订单后，再以平台订单号去重后的订单数量", // 订单量
  income_daily_target: "销售额（目标）/ 本月总天数",
  income_need_finish: "日均销售额 * 当月已过天数(包含今天)",
  income_finish: "交易类型“付款”+“退款”+“其他”的“收入”金额",
  income_need_finish_rate: "当期销售额达成率(%)= 销售额(实际)/当期应完成销售额(目标)* 100%", // 当期销售额达成率
  gross_profit_need_finish_rate: "当期销售毛利达成率(%)= 销售毛利(实际)/当期应完成销售毛利(目标)* 100% ", // 当期销售毛利达成率
  income_achieving_rate: "销售额达成率（%）=销售额（实际）/销售额(目标)* 100%", // 销售额达成率
  m2m_growth_income: `1. 当查询时间是本月时，本周期（最近30天，不含今天）的销售额 - 上周期（前一个30天）的销售额<br/>2. 当查询时间不是本月时，按对应月份作为一个周期，再查询前一个月的销售额，计算增长销售额`, // 环比增长销售额
  m2m_growth_income_rate: "环比销售额增长率 = 环比增长销售额 / 上期的销售额 * 100%", // 环比销售额增长率
  gross_profit_daily_target: "日均销售毛利（目标）= 日均销售毛利（目标）/ 本月总天数", // 日均销售毛利
  gross_profit_need_finish: "当期应完成销售毛利（目标）= 日均销售毛利 * 当月已过天数(包含今天)", // 当期应完成销售毛利
  gross_profit_achieving_rate: "销售毛利率达成率（%）=销售额（实际）/销售额(目标)* 100%", // 销售毛利率达成率
  m2m_growth_gross_profit: `1. 当查询时间是本月时，本周期（最近30天，不含今天）的销售毛利 - 上周期（前一个30天）的销售毛利，计算环比增长销售毛利<br/>2. 当查询时间不是本月时，按对应月份作为一个周期，再查询前一个月的销售毛利，计算环比增长销售毛利`, // 环比增长销售毛利
  m2m_growth_gross_profit_rate: "环比销售毛利增长率 = 环比增长销售毛利 / 上周期的销售毛利 * 100%", // 环比销售毛利增长率

  sale_gross_rate: "销售毛利率（%）=销售毛利（实际）/销售额（实际）* 100%", // 销售毛利率

  m2m_growth_order_quantity:
    " 1. 当查询时间是本月时，本周期（最近30天，不含今天）的订单量 - 上周期（前一个30天）的订单量<br/>2. 当查询时间不是本月时，按对应月份作为一个周期，再查询前一个月的订单量，计算增长订单量", //环比增长订单量

  m2m_growth_order_quantity_rate: "环比订单量增长率（%）=环比增长订单量 / 上期的订单量 * 100%", // 环比订单量增长率
}
// 当期订单量达成率
const rateTip = {
  order_quantity_achieving_rate: "订单量 的汇总 /订单量(目标)的汇总 * 100%",
  order_quantity_need_finish_rate: "订单量(实际) 的汇总 /当期应完成订单量(目标) 的汇总 * 100%",
  income_need_finish_rate: "销售额(实际)的汇总 / 当期应完成销售额(目标)的汇总 * 100%",
  gross_profit_need_finish_rate: "销售毛利(实际) 的汇总 /当期应完成销售毛利(目标)的汇总 * 100%",
  income_achieving_rate: "销售额（实际）的汇总 / 销售额(目标) 的汇总* 100%",
  m2m_growth_income_rate: "环比增长销售额汇总/对应上周期（前一个30天）的销售额 的 汇总 * 100%",
  gross_profit_achieving_rate: "销售额（实际）的汇总 /销售额(目标)的汇总 * 100%",
  sale_gross_rate: "销售毛利（实际）的汇总 / 销售额（实际）的汇总 * 100%",
  m2m_growth_gross_profit_rate: "环比增长销售毛利 的汇总 /  上周期（前一个30天）的销售毛利的汇总 * 100%",
  m2m_growth_order_quantity_rate: "环比增长订单量 的汇总  / 上期的订单量  的汇总  * 100%",
}

onMounted(async () => {
  nextTick(async () => {
    let field = await TableColumnConfigRef?.value?.getColumn()

    initTable(field)
  })
})
const initTableColumn = (field) => {
  initTable(field)
  tableRef?.value.query()
}
const initTable = (field) => {
  field = field.params.map((v) => v.value)
  let columns = TableColumnConfigRef?.value.sortedArray(columnsConfig, field)
  tableRef?.value?.$table.loadColumn([
    { type: "seq", fixed: "left", width: 55 },
    {
      width: 160,
      title: "销售人员",
      field: "salesman",
      fixed: "left",
      slots: {
        header: ({}) => <span>{target_type.value == 1 ? "销售团队" : "销售人员"} </span>,
        default: ({ row }) => <span>{target_type.value == 1 ? row.name : row.salesman}</span>,
      },
    },
    ...columns,
  ])
}

const formOption = ref({
  inline: true,
})

const fieldList = ref([
  {
    field: "target_type",
    type: "select",
    options: {
      data: [
        { label: "部门目标", value: "1" },
        { label: "个人目标", value: "2" },
      ],
      placeholder: "目标类型",
    },
    clearable: false,
    style: { width: "120px" },
    change: (e, formData) => {
      formData.sale_id = []
      formData.department_id = []
    },
  },

  // {
  //   field: "sale_id",
  //   type: "cascader",
  //   itemProps: { placeholder: "销售人员" },
  //   ...publicStyle,
  // },
  {
    field: "timeRange",
    type: "dateTimeRangeNorm",
    select: [{ label: "付款时间", value: "time_range" }],
    itemProps: { type: "month", format: "YYYY-MM", valueFormat: "YYYY-MM", shortcuts: [], clearable: false },
    ...publicStyle,
  },
  {
    field: "currency",
    type: "select",
    options: {
      data: [
        { label: "CNY", value: "CNY" },
        { label: "USD", value: "USD" },
      ],
      placeholder: "币种",
    },
    clearable: false,
    style: { width: "120px" },
  },
  {
    field: "sale_id",
    type: "cascader",
    itemProps: { placeholder: "销售人员" },
    ...publicStyle,
    show: ({ model }) => {
      return model.target_type == 2
    },
  },
  {
    field: "department_id",
    type: "cascader",
    cascaderType: "department",
    itemProps: { placeholder: "销售团队" },
    ...publicStyle,
    show: ({ model }) => {
      return model.target_type == 1
    },
  },
])
import { parseTime } from "@/utils/ruoyi"
const getTime = () => {
  return parseTime(new Date(), "{y}-{m}")
}
const columnsConfig = [
  // { width: 160, title: "销售人员", field: "salesman", slots: { header: "HeaderContent" } },
  { title: "订单量", field: "order_quantity_finish", minWidth: 130, sortable: true, noCurrency: true, slots: { header: "HeaderContent" } },
  { title: "订单量（目标）", field: "order_quantity_target", minWidth: 130, sortable: true, noCurrency: true, slots: { header: "HeaderContent" } },
  { title: "日均订单量(目标)", field: "order_quantity_daily_target", minWidth: 130, sortable: true, noCurrency: true, slots: { header: "HeaderContent" } },
  { title: "当期应完成订单量(目标)", field: "order_quantity_need_finish", minWidth: 180, sortable: true, noCurrency: true, slots: { header: "HeaderContent" } },
  {
    title: "订单量达成率",
    field: "order_quantity_achieving_rate",
    minWidth: 130,
    sortable: true,
    noCurrency: true,
    slots: {
      header: "HeaderContent",
      footer: "footerRate",
      default: "RateTem",
    },
  },
  {
    title: "当期订单量达成率",
    field: "order_quantity_need_finish_rate",
    minWidth: 140,
    sortable: true,
    noCurrency: true,
    slots: { header: "HeaderContent", footer: "footerRate", default: "RateTem" },
  },
  { title: "销售额（目标）", field: "income_target", minWidth: 130, sortable: true, slots: { header: "HeaderContent" } },
  { title: "日均销售额（目标）", field: "income_daily_target", minWidth: 150, sortable: true, slots: { header: "HeaderContent" } },
  { title: "当期应完成销售额（目标）", field: "income_need_finish", minWidth: 190, sortable: true, slots: { header: "HeaderContent" } },
  { title: "销售额（实际）", field: "income_finish", minWidth: 120, sortable: true, slots: { header: "HeaderContent" } },

  { title: "当期销售额达成率", field: "income_need_finish_rate", minWidth: 140, sortable: true, slots: { header: "HeaderContent", footer: "footerRate", default: "RateTem" } },
  { title: "当期销售毛利达成率", field: "gross_profit_need_finish_rate", minWidth: 150, sortable: true, slots: { header: "HeaderContent", footer: "footerRate", default: "RateTem" } },
  { title: "销售额达成率", field: "income_achieving_rate", minWidth: 120, sortable: true, slots: { header: "HeaderContent", footer: "footerRate", default: "RateTem" } },
  { title: "环比增长销售额", field: "m2m_growth_income", minWidth: 120, sortable: true, slots: { header: "HeaderContent" } },
  { title: "环比销售额增长率", field: "m2m_growth_income_rate", minWidth: 140, sortable: true, slots: { header: "HeaderContent", footer: "footerRate", default: "RateTem" } },
  { title: "销售毛利（目标）", field: "gross_profit_target", minWidth: 140, sortable: true, slots: { header: "HeaderContent" } },
  { title: "日均销售毛利（目标）", field: "gross_profit_daily_target", minWidth: 170, sortable: true, slots: { header: "HeaderContent" } },
  { title: "当期应完成销售毛利（目标）", minWidth: 210, sortable: true, field: "gross_profit_need_finish", slots: { header: "HeaderContent" } },
  { title: "销售毛利（实际）", field: "gross_profit_finish", minWidth: 140, sortable: true, slots: { header: "HeaderContent" } },
  { title: "销售毛利率达成率", field: "gross_profit_achieving_rate", minWidth: 140, sortable: true, slots: { header: "HeaderContent", footer: "footerRate", default: "RateTem" } },
  { title: "销售毛利率", field: "sale_gross_rate", minWidth: 140, sortable: true, slots: { header: "HeaderContent", footer: "footerRate", default: "RateTem" } },
  { title: "环比增长销售毛利", field: "m2m_growth_gross_profit", minWidth: 140, sortable: true, slots: { header: "HeaderContent" } },
  { title: "环比销售毛利增长率", field: "m2m_growth_gross_profit_rate", minWidth: 150, sortable: true, slots: { header: "HeaderContent", footer: "footerRate", default: "RateTem" } },

  { title: "环比增长订单量", field: "m2m_growth_order_quantity", minWidth: 150, sortable: true, slots: { header: "HeaderContent" } },
  { title: "环比订单量增长率", field: "m2m_growth_order_quantity_rate", minWidth: 150, sortable: true, slots: { header: "HeaderContent", footer: "footerRate", default: "RateTem" } },
]
// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      sale_id: [""],
      currency: "CNY",
      target_type: "2",
      timeRange: { type: "time_range", value: getTime() },
    },
  },
  showFooter: true,
  showOverflow: true,
  sortConfig: {
    remote: false,
    defaultSort: {
      field: "income_finish",
      order: "desc",
    },
  },
  columns: [],
  pagerConfig: {
    pageNum: 1,
    pageSize: 100,
    pageSizes: [100, 150, 200],
  },
  footerMethod() {
    return summary.value
  },
  proxyConfig: {
    ajax: {
      query: async ({ page, form }) => {
        currency.value = form.currency
        let params = { ...form, ...page }
        params.time_range = [`${params.time_range}-01 00:00:00`, `${getLastDayOfMonth(params.time_range)} 23:59:59`]
        target_type.value = form.target_type
        let res = await kpiMember(params)
        summary.value = []
        if (form.target_type == 2) {
          rateKeys.forEach((k) => {
            res.data.summary[k] = res.data.summary[k] + "%"
          })
          res.data.summary.salesman = "合计"
          if (res.data.summary) {
            summary.value = [{ ...res.data.summary }]
          }
        }

        res.data = res.data.list
        return res
      },
    },
  },
})
const rateKeys = [
  "order_quantity_achieving_rate",
  "order_quantity_need_finish_rate",
  "income_need_finish_rate",
  "gross_profit_need_finish_rate",
  "income_achieving_rate",
  "m2m_growth_income_rate",
  "gross_profit_achieving_rate",
  "sale_gross_rate",
  "m2m_growth_gross_profit_rate",
  "m2m_growth_order_quantity_rate",
]

const summary = ref([])
const target_type = ref("2")
const currency = ref("")
const getLastDayOfMonth = (date) => {
  let year = date.split("-")[0]
  let month = date.split("-")[1]
  return parseTime(new Date(year, month, 0), "{y}-{m}-{d}")
}
defineExpose({})
</script>

<style lang="scss" scoped>
:deep(.vxe-table--footer) {
  .vxe-footer--column {
    background: var(--base-table-header-bg-color);
  }
}
</style>
